package com.fjut.kms.dao;

import com.fjut.kms.domain.UserLicense;
import com.fjut.kms.tools.DBTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Empathy on 2017/7/30.
 */
public class UserLicenseJDBCImpl implements UserLicenseDao{

    private static final String SQL_GET_BYUSERNAME="select * from userLicense where username=?";
    private static final String SQL_GET_BUSOFTNAME="select * from userLicense where username=? and softName=?";
    public List<UserLicense> getUserLicense(String userName){
        Connection conn= DBTools.getConn();
        PreparedStatement pstmt=null;
        ResultSet rset =null;
        List<UserLicense> ulList=new ArrayList<UserLicense>();
        try{
            pstmt=conn.prepareStatement(SQL_GET_BYUSERNAME);
            pstmt.setString(1,userName);
            rset=pstmt.executeQuery();
            while (rset.next()){
                UserLicense ul=new UserLicense();
                ul.setUserName(userName);
                ul.setSoftName(rset.getString("softname"));
                ul.setActivated(Integer.parseInt(rset.getString("activated")));
                ul.setAssigned(Integer.parseInt(rset.getString("assigned")));
                ulList.add(ul);
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
        return ulList.size()>0?ulList:null;
    }

    public UserLicense getUserLicenseBySoftName(String userName,String softName){
        Connection conn= DBTools.getConn();
        PreparedStatement pstmt=null;
        ResultSet rset =null;
        UserLicense ul=null;
        try{
            pstmt=conn.prepareStatement(SQL_GET_BUSOFTNAME);
            pstmt.setString(1,userName);
            pstmt.setString(2,softName);
            rset=pstmt.executeQuery();
            if (rset.next()){
                ul.setSoftName(softName);
                ul.setAssigned(Integer.parseInt(rset.getString("assigned")));
                ul.setActivated(Integer.parseInt(rset.getString("activated")));
            }


        }catch (SQLException e){
            e.printStackTrace();
        }
        return ul!=null?ul:null;
    }

}
